package com.example.ten_minutes_more;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Timer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PopupActivity extends Activity{
	
	Button exit, delay;
	TextView time,hour,min;
	public static int id;
	Context context;
	int alarmHour, alarmMin;
	Timer timeTimer;
	Database db;
	MediaPlayer mMediaPlayer;
	AudioManager audioManager;
	Thread thread;
	int runnable_m;
	int runnable_s;
	TextView popup_time;
	MyHandler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		
		id = getIntent().getIntExtra("reqCode", 0);
		
		Database db = new Database(PopupActivity.this);
		db.open();
		
		GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
		int date = currentCalendar.get(Calendar.DAY_OF_WEEK);
		
		switch(date){
		case 1: // sun
			if(!db.isCheckedSun(id))
				return;
			break;
		case 2: // mon
			if(!db.isCheckedMon(id))
				return;
			break;
		case 3: // sun
			if(!db.isCheckedTue(id))
				return;
			break;
		case 4: // sun
			if(!db.isCheckedWed(id))
				return;
			break;
		case 5: // sun
			if(!db.isCheckedThu(id))
				return;
			break;
		case 6: // sun
			if(!db.isCheckedFri(id))
				return;
			break;
		case 7: // sun
			if(!db.isCheckedSat(id))
				return;
			break;
			
		}
		
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.popup);
	    
	    db = new Database(context);
		db.open();
		
	    exit = (Button) findViewById(R.id.delete_popup);
	    delay = (Button) findViewById(R.id.delay_btn);
	    time = (TextView) findViewById(R.id.popup_time);
	    hour = (TextView) findViewById(R.id.popup_hour);
	    min = (TextView) findViewById(R.id.popup_min);
	    
	    long time = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);
		
	    int h = c.get(Calendar.HOUR_OF_DAY);
		int m = c.get(Calendar.MINUTE);

		hour.setText(Integer.toString(h));
		min.setText(Integer.toString(m));
		
	    exit.setOnClickListener(l);
	    delay.setOnClickListener(l);
	    
	    context = getApplicationContext();
	   
	    alarmHour = db.getHour(id);
	    alarmMin = db.getMin(id);
	    
	    //timeTimer = new Timer();
        //timeTimer.schedule(timeTimerTask, 30, 1000);
	    
	    popup_time = (TextView)findViewById(R.id.popup_time);
	    handler = new MyHandler();
	    BackThread thread = new BackThread();
	    thread.setDaemon(true);
	    thread.start();
	   
	    mMediaPlayer = new MediaPlayer();
	    audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);    
	    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	       
	    int setting_volume = db.getVolume(id);
	    
	    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, setting_volume, AudioManager.FLAG_PLAY_SOUND);
	    String musicID = db.getMusicID(id);
		Uri uri = Uri.withAppendedPath(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "" + musicID);
		playAudio(uri);
	}
	
	public void playAudio(Uri uri){	
		try {
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(this, uri);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	 @Override
	 public void onDestroy() {
	     super.onDestroy();
	     /* Release resources allocated to player */
	     mMediaPlayer.reset();
	     mMediaPlayer.release();
	     mMediaPlayer = null;
	 }
	
	 class BackThread extends Thread{
			public void run(){
				while(true){
					runnable_s++;
					if(runnable_s > 59){
						runnable_s = 0;
						runnable_m++;
					}
					
					Message msg = Message.obtain(handler, 0, runnable_s, 0);
					handler.sendMessage(msg);
					try{
						Thread.sleep(1000);				
					}catch(InterruptedException e){
						;
					}			
				}
			}
		}
		
		class MyHandler extends Handler{
			@Override
			public void handleMessage(Message msg){
				if(msg.what == 0)
					popup_time.setText(runnable_m + "분 " + msg.arg1 + "초가 지났습니다");
			}
		}
	
	Button.OnClickListener l = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.delete_popup:
				// 게임 실행 
				int game = db.getGame(id);
				
				switch(game){
				case 0:
					finish();
					break;
				case 1: 
					Intent text = new Intent(PopupActivity.this, Text.class);
					startActivity(text);
					finish();
					break;
				case 2 :
					Intent multi = new Intent(PopupActivity.this, Multi.class);
					startActivity(multi);
					finish();
					break;
				}
				break;
			case R.id.delay_btn:
				// 알람 지연 화면 실행
				Intent delay = new Intent(PopupActivity.this, DelayAlarm.class);
				delay.putExtra("id", id);
				startActivity(delay);
				finish();
				break;
			}
			
		}
		
	};
	/*
	
    TimerTask timeTimerTask = new TimerTask(){
        public void run(){
            
        	GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
        	final int curHour = currentCalendar.get(Calendar.HOUR);
        	final int curMin = currentCalendar.get(Calendar.MINUTE);
        	
        	
        	final String after = "초기알람시간("+alarmHour+":"+alarmMin+")으로 부터\n+"
        					+(curHour-alarmHour)+":"+(curMin-alarmMin); 
           
        	
            Handler timeHandler = time.getHandler();
            timeHandler.post(new Runnable(){
                public void run(){
                    Log.d("timeTimerTask", "Time : " + time);     
                    time.setText(after);
                    hour.setText(String.valueOf(curHour));
                    min.setText(String.valueOf(curMin));
                }
            }); 
        } //end run
    }; //end TimerTask

    protected void onStop() {
        timeTimerTask.cancel();  
        timeTimer.cancel(); 
        super.onStop();
    }*/
}
